<script lang="ts" setup name="XtxCity">
import { ref, watch } from 'vue';
import axios from 'axios';
import { onClickOutside } from '@vueuse/core'
const cityList = ref<CityItem[]>([])
const cacheList = ref<CityItem[]>([])
const target = ref(null)
const active = ref(false)
const userAddress = ref('')

// 优化弹出框，点击外面把弹出框关闭
onClickOutside(target, () => {
  // console.log('点击了外面');
  active.value = false
})

type CityItem = {
  code: string
  level: number
  name: string
  areaList: CityItem[]
}
// 定义一个方法获取城市的数据
async function getCityList() {
  const res = await axios.get<CityItem[]>('https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json')
  // console.log(res)
  cityList.value = res.data
  cacheList.value = res.data
}
//  调用获取城市数据的方法
getCityList()
const selectCity = (city: CityItem) => {
  userAddress.value = userAddress.value + ' ' + city.name
  if(!city.areaList) return active.value = false
  cityList.value = city.areaList
  
}

// 监听弹窗，如果弹窗关闭就重置城市数据
watch(active,(value) => {
  if(!value) {
    cityList.value = cacheList.value
  }
})

</script>
<template>
  <div class="xtx-city" ref="target">
    <div class="select" @click="active = !active" :class="{ active }">
      <span class="value" v-if="userAddress">{{ userAddress }}</span>
      <span class="placeholder" v-else>请选择配送地址</span>
      <i class="iconfont icon-angle-down"></i>
    </div>
    <div class="option" v-show="active">
      <span @click="selectCity(item)" class="ellipsis" v-for="item in cityList" :key="item.name">{{ item.name }}</span>
    </div>
  </div>
</template>

<style scoped lang="less">
.xtx-city {
  display: inline-block;
  position: relative;
  z-index: 400;
  .select {
    border: 1px solid #e4e4e4;
    height: 30px;
    padding: 0 5px;
    line-height: 28px;
    cursor: pointer;
    &.active {
      background: #fff;
    }
    .placeholder {
      color: #999;
    }
    .value {
      color: #666;
      font-size: 12px;
    }
    i {
      font-size: 12px;
      margin-left: 5px;
    }
  }
  .option {
    width: 542px;
    border: 1px solid #e4e4e4;
    position: absolute;
    left: 0;
    top: 29px;
    background: #fff;
    min-height: 30px;
    line-height: 30px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    > span {
      width: 130px;
      text-align: center;
      cursor: pointer;
      border-radius: 4px;
      padding: 0 3px;
      &:hover {
        background: #f5f5f5;
      }
    }
  }
}
</style>